package source.view;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.*;
import javax.swing.border.LineBorder;

import source.controller.CustomKeyFileManager;
import source.controller.PlayerKeyListener;

/**
 * Dialog box that comes up displaying the current Key Map.  This box allows
 * the user to set his/her own key map.  
 * @author Steve
 *
 */
public class KeyMapDialog extends JDialog {
	private PlayerKeyListener pk;
	
	public KeyMapDialog(Frame frame, PlayerKeyListener pk){
		super(frame, true);
		this.pk = pk;
		
		setSize(300,630);
		
		// We want to calculate how many keys are assigned
		int noOfKeys = 0;
		String[] keys = pk.getKeyMap();
		for(int i = 0; i < keys.length; i++){
			if(keys[i].length() > 0) noOfKeys++;
		}
		GridLayout layout = new GridLayout(noOfKeys+1, 2);
		layout.setHgap(5);
		layout.setVgap(1);
		setLayout(layout);
		
		KeyMapDialogListener mcl = new KeyMapDialogListener(this);
		for(int i = 0; i < keys.length; i++){
			if(keys[i].length() > 0){
				this.add(new JLabel(keys[i]));
				
				KeyMapLabel label = new KeyMapLabel(KeyEvent.getKeyText(i), keys[i]);
				label.setOpaque(false);
				label.setBackground(Color.RED);
				label.setBorder(LineBorder.createBlackLineBorder());
				label.setFocusable(true);
				label.setName(keys[i]);
				label.setHorizontalAlignment(JLabel.CENTER);

				label.addKeyListener(mcl);
				label.addMouseListener(mcl);
				this.add(label);
			}
		}
		
		JButton submit = new JButton("OK");
		submit.setName("submit");
		submit.addMouseListener(mcl);
		this.add(submit);
		
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		setTitle("Keypad Configuration");
		this.setFocusTraversalKeysEnabled(false);
	}
	
	public boolean requestKeyChange(String id, int newKeyCode)
	{
		return pk.requestKeyChange(id, newKeyCode);
	}
	
}
